import React, { useEffect, useRef, useState } from 'react'
import { ActivityIndicator, Dimensions, FlatList, ScrollView, StyleSheet, View } from 'react-native'
import { activeCategoryIdAtom, categoryItemType, categoryListAtom, stickerDataAtom, SwiperItem, swiperListAtom } from '@/store/home'
import { useAtom } from 'jotai'
import { getCategoryServer, getClientListServer, getUserImgListServer } from '@/servers/app-servers'
import { fullImagePath, manageColor, manageCoverimage, manmageDecorate } from '@/utils/manageData'
import HomeSwiper from './components/HomeSwiper'
import HomeTabs from './components/HomeTabs'
import TransitionLoading from '@/components/TransitionLoading'
import TempScene from './components/comtemp/TempScene/TempScene'
import TempSticker from './components/comtemp/TempSticker/TempSticker'
import TempFaceSwap from './components/comtemp/TempFaceSwap/TempFaceSwap'
import { vh, vw } from '@/common/dimensions'
import { UserImgItemType, userImgListAtom, userImgParamsAtom, userInfoAtom } from '@/store/user'
import HomeTips from './components/HomeTips'
import ParallaxScrollView from '@/components/ParallaxScrollView'
import { useUserImgList } from '@/hooks/useUserImgList'
import { useResultShow } from '@/hooks/useResultShow'
import ResultShow from './ResultShow'
import { useUpdateUserInfo } from '@/hooks/useUpdateUserInfo'

const { width } = Dimensions.get('window'); // 获取屏幕宽度

export default function Home() {
    // 首页频道列表
    const [categoryList, setCategoryList] = useAtom(categoryListAtom)
    // 当前选中的频道id
    const [activeCategoryId, setActiveCategoryId] = useAtom(activeCategoryIdAtom)
    // 当前 FlatList 页面的索引
    const [activeIndex, setActiveIndex] = useState<number>(0); 
    // 首页轮播图数据
    const [swiperList , setSwiperList] = useAtom(swiperListAtom)
    // 当前用户信息
    const [userInfo , setUserInfo] = useAtom(userInfoAtom)
    // 标记初次加载
    const [isCategoryLoaded, setIsCategoryLoaded] = useState(false);  
    // 用来存储每个页面的高度
    const [contentHeights, setContentHeights] = useState<number[]>([]); 
    // 页面初始化时的 loading 状态
    const [loading, setLoading] = useState<boolean>(true); 
    // 创建 ref 获取FlatList
    const flatListRef = useRef<FlatList>(null);
    // stickerData 数据
    const [stickerData , setStickerData] = useAtom(stickerDataAtom)
    // 使用自定义 Hook  获取用户图片列表
    const { getUserImgList } = useUserImgList();
    // 自定义hook  获取作品页展示
    const { getResultShow } = useResultShow()
    // 自定义hook  UpdateUserInfo
    const { updateUserInfo } = useUpdateUserInfo()
    // 获取频道列表
    const getCategoryList = async () => {
        const res = await getCategoryServer()
        let { list , banner_list} = res.data
        const updatedList = list.map((item: any) => {
            item.json_content.icon_cn = fullImagePath(item.json_content.icon_cn);
            item.json_content.icon_all = fullImagePath(item.json_content.icon_all);
            item.sceneList = []
            item.loading = true
            return item
        })
        setCategoryList(updatedList)
        setActiveCategoryId(updatedList[0].id)
        let otherList: string[] = [];
        const idMinusOneItem = banner_list.find((item: SwiperItem) => item.id === -1);// 尝试查找 id === -1 的项并生成其列表
        if (idMinusOneItem && idMinusOneItem.cover_image_cn) {
            otherList = idMinusOneItem.cover_image_cn.split(",").map((p: string) => fullImagePath(p));
        }
        banner_list.forEach((item: SwiperItem) => {
            if (item.cover_image_cn) {
                item.list = item.cover_image_cn.split(',').map((p: string) => fullImagePath(p));
            } else {
                item.list = otherList;
            }
        });
        setSwiperList(banner_list)
        setIsCategoryLoaded(true);  // 设置为 true，表示已经加载过分类列表
    }


    // 获取首页频道内容信息
    const getClientList = async (id: number , force:boolean = false) => {
        // 发请求前判断是否存在了
        let foundCategory: categoryItemType = (categoryList.find((item: categoryItemType) => item.id === id) as categoryItemType)
        if (!foundCategory) return;
        if ( force || !foundCategory.sceneList.length) {
            console.log("需要请求接口");
            foundCategory.loading = true;
            setCategoryList([...categoryList])
            const res = await getClientListServer(id)
            const {list , sticker_data:{color_list , decorate_list} } = res.data
            foundCategory.sceneList = manageCoverimage(list , userInfo)
            foundCategory.loading = false;
            setCategoryList([...categoryList]);  // 更新 categoryList 以触发重新渲染
            // 判断 atom 中有没有缓存
            if( "colorList" in stickerData && !Object.keys(stickerData?.colorList).length){
                console.log("处理setStickerData");
                const decorateList = manmageDecorate(decorate_list)
                const colorList = manageColor(color_list)
                setStickerData({decorateList ,colorList})
            }
        } else {
            console.log("已经有数据了");
            return
        }
        setLoading(false); // 数据加载完成，取消 loading 状态
    }
    
    // 翻页动画结束
    const handleScrollEnd = (event: { nativeEvent: { contentOffset: { x: number } } }) => {
        // 通过水平偏移量计算当前页索引
        const offsetX = event.nativeEvent.contentOffset.x;  // 当前偏移量
        const computedMove = offsetX / width;               // 计算滑动的页面比例
        let current = activeIndex;
        let MoveC0 = 0.1
        // 判断滑动方向
        if (computedMove > activeIndex) {
            // 向右滑动，如果超过MoveC0系数个页面宽度，current+1
            if (computedMove - activeIndex > MoveC0) {
                current += 1;
            }
        } else if (computedMove < activeIndex) {
            // 向左滑动，如果超过MoveC0系数个页面宽度，current-1
            if (activeIndex - computedMove > MoveC0) {
                current -= 1;
            }
        }
        setActiveIndex(current);  // 更新当前索引
        if(categoryList[current].id){
            changeCategory(categoryList[current].id)
        }
    }

    // 点击频道
    const changeCategory = (id:number) => {
        const index = categoryList.findIndex((category) => category.id === id);
        if (index !== -1) {
            try {
                flatListRef.current?.scrollToIndex({ index, animated: true });
            } catch (e) {
                console.warn("scrollToIndex failed", e);
            }
        }
        setActiveCategoryId(id)
        getClientList(id)
        //  更新当前索引  且 如果高度存在，则调用动态调整高度的方法
        setActiveIndex(index);  
        if (contentHeights[index] ) {
            onPageContentChange(index, width, contentHeights[index]); 
        }
    }

   // 动态调整页面高度
    const onPageContentChange = (index: number, w: number, h: number) => {
        const updatedHeights = [...contentHeights];
        updatedHeights[index] = Math.ceil(h);
        setContentHeights(updatedHeights);
    };
    
    // FlatList 每个item的渲染事件  React.memo 来防止不必要的重新渲染
    const renderScene = ({ item , index }: { item: categoryItemType , index:number }) => {
        let { sceneList , loading } = item; // 解构出 sceneList
        if(loading){
            return (
                <View style={styles.loadingContainer}>
                    <ActivityIndicator size="large" color="#0000ff" />
                </View>
            )
        }
        return (
            /* 
            最外层一定要禁用滚动和滚动条
            */
            <ScrollView
                showsVerticalScrollIndicator={false} 
                scrollEnabled={false}
                contentContainerStyle={styles.sceneWrapper}
                onContentSizeChange={(w, h) => onPageContentChange(index, w, h)} // 动态调整页面内容的高度
            >
                {
                    !!sceneList.length && (
                        sceneList.map((sceneItem , index) =>{
                            let { type } = sceneItem
                            if(type === 'scene' || type === 'styler'){
                                return <TempScene key={sceneItem.id} sceneItem={sceneItem} />
                            }
                            if(type === 'sticker'){
                                return <TempSticker key={sceneItem.id} sceneItem={sceneItem} /> 
                            }
                            if(type === "face_swap"){
                                return <TempFaceSwap key={sceneItem.id} sceneItem={sceneItem} />
                            }
                        })
                    )
                }
            </ScrollView>
        )
    }


    useEffect(() => {
        getCategoryList()
        getUserImgList()
        getResultShow()
        updateUserInfo()
    }, [])

    useEffect(() => {
        if (isCategoryLoaded && categoryList.length > 0 && userInfo) {
            getClientList(categoryList[0].id);
        }
    }, [isCategoryLoaded]);
 
    useEffect(()=>{
        console.log("监听 userInfo?.points.free_times");
        
        getClientList(activeCategoryId , true)
    },[userInfo?.points.free_times])

    if (loading) {
        return <TransitionLoading /> // 数据未加载时显示加载指示器
    }
 

    return (
        <ParallaxScrollView
            headerBackgroundColor={{ light: "#D0D0D0", dark: "#353636" }}
            headerImage={<HomeSwiper swiperList={swiperList} activeCategoryId={activeCategoryId} />}
        >
            <View style={[styles.main,{ height: contentHeights[activeIndex] + 200 || 1000 }]} pointerEvents="box-none">
                {/* tabs组件 */}
                <HomeTabs categoryList={categoryList} activeCategoryId={activeCategoryId} changeCategory={changeCategory} />
                {/* ResultShow */}
                <ResultShow/>
                {/* tips组件 */}
                <HomeTips />
                {/* sceneList */}
                <FlatList
                    ref={flatListRef}  // 将 ref 绑定到 FlatList
                    showsHorizontalScrollIndicator={false}
                    data={categoryList}
                    renderItem={renderScene}
                    keyExtractor={(item) => item.id.toString()} // 确保有唯一的 key
                    horizontal // 启用水平滚动
                    pagingEnabled // 启用分页效果
                    onScrollEndDrag={handleScrollEnd} // 滚动结束时触发
                    nestedScrollEnabled={true} // 启用嵌套滚动
                    extraData={contentHeights} // 添加 extraData 属性
                />
            </View>
        </ParallaxScrollView>
        // <ScrollView 
        //     showsVerticalScrollIndicator={false} 
        //     contentContainerStyle={styles.scrollContentContainer}
        // >
        //     {/* 头部轮播组件 */}
        //     <HomeSwiper swiperList={swiperList} activeCategoryId={activeCategoryId} />
        //     {/* IOS 解决兼容问题  pointerEvents 禁止main的触发滑动 但保持子元素的触摸滑动 */}
        //     <View style={[styles.main,{ height: contentHeights[activeIndex] + 200 || 1000 }]} pointerEvents="box-none">
        //         {/* tabs组件 */}
        //         <HomeTabs categoryList={categoryList} activeCategoryId={activeCategoryId} changeCategory={changeCategory} />
        //         {/* tips组件 */}
        //         <HomeTips />
        //         {/* sceneList */}
        //         <FlatList
        //             ref={flatListRef}  // 将 ref 绑定到 FlatList
        //             showsHorizontalScrollIndicator={false}
        //             data={categoryList}
        //             renderItem={renderScene}
        //             keyExtractor={(item) => item.id.toString()} // 确保有唯一的 key
        //             horizontal // 启用水平滚动
        //             pagingEnabled // 启用分页效果
        //             onScrollEndDrag={handleScrollEnd} // 滚动结束时触发
        //             nestedScrollEnabled={true} // 启用嵌套滚动
        //             extraData={contentHeights} // 添加 extraData 属性
        //         />
        //     </View>
        // </ScrollView>
    )
}
const styles = StyleSheet.create({
    main:{
        flex:1,
        paddingTop:24,
        paddingHorizontal: 2 * vw,
        backgroundColor:'#fff',
        borderTopLeftRadius: 16,
        borderTopRightRadius:16,
        transform: [{ translateY:-20}]
    },
    loadingContainer: {
        flex: 1,
        paddingTop:24,
        justifyContent: 'flex-start',
        alignItems: 'center',
        width: 96 * vw, // 保证宽度与频道的宽度一致
    },

    sceneWrapper: {
        width: 96 * vw, // 保证外层容器宽度根据窗口调整
        flexDirection: 'row',
        flexWrap: 'wrap', // 允许换行
        paddingBottom:24,
        justifyContent: 'space-between', // 根据内容间距调整
        alignItems: 'flex-start', // 确保子元素根据其内容高度从左到右排列
        backgroundColor:"#fff"
    },
    scrollContentContainer:{
        flexGrow: 1, // 使 ScrollView 根据子元素高度撑开
    }
})

